<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>AI查询</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="shortcut icon" href="./favicon.ico" />
    <script type="text/javascript" src="js/plugin/jquery.min.js"></script>
    <script type="text/javascript" src="js/plugin/jquery.cookie.js"></script>
    <script type="text/javascript" src="js/plugin/echarts/echarts.min.js"></script>
    <script type="text/javascript" src="js/plugin/echarts/charts.js"></script>
    <script type="text/javascript" src="js/plugin/tablesorter/jquery.tablesorter.js"></script>
    <script type="text/javascript" src="js/apiTest.js"></script>
    <script type="text/javascript" src="js/plugin/bootstrap-3.3.5/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/plugin/bootstrap-3.3.5/js/bootstrap-select.min.js"></script>
    <script type="text/javascript" src="js/plugin/bootstrap-3.3.5/js/defaults-zh_CN.min.js"></script>
    <script type="text/javascript" src="js/plugin/jsonview-v1.2.0/dist/jquery.jsonview.js"></script>
    <script type="text/javascript" src="js/plugin/fullscreen.js"></script>
    <script type="text/javascript" src="js/plugin/echarts/charts.js"></script>
    <script type="text/javascript" src="js/sybn_bootstrap.js"></script>
    <script type="text/javascript" src="js/sybn_common.js"></script>
    <script type="text/javascript" src="js/sybn_desc_table.js"></script>
    <script type="text/javascript" src="js/md5.js"></script>
    <script type="text/javascript" src="js/login_simple.js"></script>
    <script type="text/javascript" src="js/plugin/sql/codemirror.js"></script>
    <script type="text/javascript" src="js/plugin/sql/matchbrackets.js"></script>
    <script type="text/javascript" src="js/plugin/sql/sql.js"></script>
    <script type="text/javascript" src="js/plugin/sql/show-hint.js"></script>
    <script type="text/javascript" src="js/plugin/sql/sql-hint3.js"></script>
    <script type="text/javascript" src="js/plugin/sql/sql-hint-sybn.js"></script>
    <script type="text/javascript" src="js/plugin/gzip/pako.min.js"></script>
    <script type="text/javascript" src="js/plugin/gzip/base64_gzip.js"></script>
    <script type="text/javascript" src="js/plugin/clipboard/clipboard.min.js"></script>
    <script type="text/javascript" src="js/plugin/select2/select2.full.min.js"></script>
    <link rel="stylesheet" href="js/plugin/select2/select2.min.css" />
    <link rel="stylesheet" href="css/fontawesome-4.2.0_ie7/4.2.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="js/plugin/bootstrap-3.3.5/css/bootstrap.min.css" />
    <link rel="stylesheet" href="js/plugin/bootstrap-3.3.5/css/bootstrap-select.min.css" />
    <link rel="stylesheet" href="js/plugin/jsonview-v1.2.0/dist/jquery.jsonview.css" />
    <link rel="stylesheet" href="js/plugin/tablesorter/theme.default.min.css" />
    <link rel="stylesheet" href="css/plugin/sql/codemirror.css" />
    <link rel="stylesheet" href="css/plugin/sql/show-hint.css" />
    <link rel="stylesheet" href="css/bootstrap_sybn_custom.css" />
    <link rel="stylesheet" href="css/api_test.css" />
    <style>
        .form-control.CodeMirror{height:230px; width:100%;}
        .panel_type_xs .form-control.CodeMirror{height: 95px;width:100%;}
        .sql_input_big .form-control.CodeMirror{height: 500px}
        .sql_input_big .iframe_preview {max-height: 400px;}
        .sql_input_big2 .form-control.CodeMirror{height: 800px}
        .sql_input_big2 .iframe_preview {max-height: 500px;}
        .btn-group-xs .btn.common_use_select {padding: 0px 5px; font-size: 10px; line-height: 1.0;}
        .common_use {margin-right: 10px;}
        .loading-indicator {position: absolute;top: 0;left: 0;padding: 10%;width: 100%;height: 100%;background: rgba(225, 225, 255, 0.8);display: flex;flex-direction: column;justify-content: center;align-items: center;z-index: 1000;}
        .spinner {border: 4px solid rgba(0, 0, 0, 0.1);width: 36px;height: 36px;border-radius: 50%;border-left-color: #09f;animation: spin 1s linear infinite;}
        @keyframes spin {to {transform: rotate(360deg);}}
        iframe {width: 100%;height: 100%;border: none;position: relative;z-index: 1;}
        .ai_result hr {margin-top: 0px;margin-bottom: 0px;border: 0;border-top: 1px solid #eee}
        .ai_result b {color:#337ab7}
        .ai_result .score {color:#F33}
        .action_group select.modelName {width: 140px;}
        #p_select_gbi {min-width: 750px;}
        .common_use_select{text-align: left;}
    </style>
</head>
<body>

<ul class="nav nav-tabs">
    <li><strong class="title">AI查询</strong></li>
    <li class="active"><a href="#p_select_gbi" data-toggle="tab" aria-expanded="false">人工智能查询</a></li>
    <li class=""><a href="#p_info" data-toggle="tab" aria-expanded="false">关于</a></li>
    <li class="floatRight padding3">
        <button type="button" class="btn btn-warning btn-xs login_out">注销<span class="login_username"></span></button>
        <!-- <button type="button" class="btn btn-danger btn-xs" onclick="$('#cacheRefresh').click()">刷新缓存</button>-->
    </li>
</ul>
<div class="tab-content">

    <div id="p_select_gbi" class="panel panel-primary tab-pane active sybn-api-demo">

         <div class="panel-heading text-primary btn-group-xs">
             <span class="p_title"> bi - AI智能问答, 当前支持查询生产环境的部分报表(T05,M01)相关问题, 基于百炼工作流应用 </span>
         </div>

        <div class="panel-body sybn-api-demo collapse in">

            <div class="input-group input-group-xs sql_textarea_parent">
                 <span class="common_use btn-group-vertical input-group-addon btn-group-xs padding0">可选择常用提问:</span>
                 <select class="btn btn-default common_use_select form-control" title="常用提问" onchange="setGbiFun(this)">
                     <option value="自营渠道在2025年3月1日的票房和售票数">自营渠道在2025年3月1日的票房和售票数</option>
                     <option value="请帮我统计自营渠道2025年3月1日的票房总额和总售票量？">请帮我统计自营渠道2025年3月1日的票房总额和总售票量？</option>
                     <option value="在2025年3月1日通过自营渠道卖了多少张票？对应的票房收入是多少？">在2025年3月1日通过自营渠道卖了多少张票？对应的票房收入是多少？</option>
                     <option value="请统计自营渠道在2025年3月1日当天的票房和影票数量。">请统计该自营渠道在2025年3月1日当天的票房和影票数量。</option>
                     <option value="我需要自营渠道2025年3月1日的两项数据：票房收入和出票张数。">我需要自营渠道2025年3月1日的两项数据：票房收入和出票张数。</option>
                     <option value="调取2025年3月1日自营渠道的票房数据及出票张数。">调取2025年3月1日自营渠道的票房数据及出票张数。</option>
                     <option value="自营渠道在2025年3月1日的票房表现和出票量？">自营渠道在2025年3月1日的票房表现和出票量？</option>
                     <option value="自营渠道在2025年3月1日的单日票房和影票数量分别是多少。">自营渠道在2025年3月1日的单日票房和影票数量分别是多少。</option>
                     <option value="2025年3月1日，通过自有渠道实现的票房收入及影票张数是多少？">2025年3月1日，通过自有渠道实现的票房收入及影票张数是多少？</option>
                     <option value="我需要两项数据：2025年3月1日，①自营渠道的票房金额，②当天该渠道售出的总票数。">我需要两项数据：2025年3月1日，①自营渠道的票房金额，②当天该渠道售出的总票数。</option>
                 </select>
            </div>
            <div class="input-group input-group-xs sql_textarea_parent">
                <span class="common_use btn-group-vertical input-group-addon btn-group-xs padding0">我的历史提问:</span>
                <select class="btn btn-default common_use_select form-control history_select" title="历史提问" onchange="replayHistory(this)">
                </select>
            </div>

            <div class="row">
                <div class="col-sm-6">
                    <div class="input-group input-group-xs">
                        <span class="common_use btn-group-vertical input-group-addon btn-group-xs padding0">租户:</span>
                        <select name="tenant_id" class="form-control tenant_select">
                            <option value="756142">[756142]未知激光影城九龙坡店</option>
                        </select>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="input-group input-group-xs">
                        <span class="common_use btn-group-vertical input-group-addon btn-group-xs padding0">影院:</span>
                        <select name="cinema_id" class="form-control cinema_select"></select>
                    </div>
                </div>
            </div>

            <div class="input-group input-group-xs sql_textarea_parent">
                <textarea name="userQuery" rows="5" class="form-control" style="height:100px;">今天的按省份的票房</textarea>

                <span class="btn-group-vertical input-group-addon input-group-xs padding0 action_group">
                    <select class="btn btn-default modelName form-control" name="cacheAble">
                        <option value="false" selected="selected">禁止缓存ai结果</option>
                        <option value="true">允许缓存ai结果</option>
                    </select>
                    <select class="btn btn-default modelName form-control" name="apiVersion">
                        <option value="java_0603" selected="selected">java_0603</option>
                        <option value="java_0417">java_0417</option>
                        <option value="bailian_flow_cx_0417">百炼工作流_0417</option>
                        <option value="bailian_flow_cx_0411">百炼工作流_0411</option>
                        <!--                        <option value="bailian_flow_lpf_0411">百炼工作流_lpf_0411</option>-->
                    </select>
                    <select class="btn btn-default modelName form-control" name="modelName">
                        <option value="qwq-plus" selected="selected">qwq-plus</option>
                        <option value="qwen-coder-plus">qwen-coder-plus</option>
                        <option value="deepseek-r1">deepseek-r1</option>
                    </select>
                    <span class="btn btn-default gbiApi submit form-control">提问</span>
                </span>
            </div>
            <div class="input-group input-group-xs iframe-container ai_result" style="width:100%; height:500px;">
                <div class="loading-indicator" id="loadingIndicator">
                    <div class="spinner"></div>
                    <p id="view_param">Loading...</p>
                </div>
                <span id="knowledge" rows="15"></span>
                <span><b>结果:</b></span>
                <textarea id="resultMsg" rows="20"></textarea>
                <span id="prompt"></span>
                <div id="outputTable"></div>
            </div>
        </div>
    </div>

    <div id="p_info" class="panel panel-primary tab-pane">
        <div class="panel-heading text-primary">
            <span class="p_title">关于 About</span>
        </div>
        <div class="panel-body sybn-api-demo collapse in">

            <div class="panel panel-success w100">
                <div class="panel-heading text-primary">
                    <span class="p_title">服务器状态</span>
                </div>
                <div class="panel-body sybn-api-demo collapse in">
                    <iframe title="info" class="json_iframe" src="info_vue.html?r=60"></iframe>
                </div>
            </div>

            <div class="panel panel-success w100">
                <div class="panel-heading text-primary">
                    <span class="p_title">重要更新: 2024-04-02</span>
                </div>
                <div class="panel-body collapse in change_log">
                    <p>
                        <strong>2025-01-02</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/gzip/gzip.html" target="_blank">gzip工具</a></span>
                    </p>
                    <p>
                        <strong>2024-04-02</strong><br/>
                        <span class="change_log_line">
                            <span>sql 翻译工具: </span>
                            <a href="js/plugin/mergely/examples/replace_clickhouse.html" target="_blank">to clickhouse </a> |
                            <a href="js/plugin/mergely/examples/replace_holo.html" target="_blank">to holo </a> |
                            <a href="js/plugin/mergely/examples/replace_flink.html" target="_blank">to flink </a>
                        </span>
                        <br/>
                        <span class="change_log_line">
                            <span>对比工具: </span>
                            <a href="js/plugin/mergely/examples/compare_tables.html" target="_blank">列表相似度对比 </a>
                        </span>
                    </p>
                    <p>
                        <strong>2023-05-29</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/viz/viz_java.html" target="_blank">java调用关系图</a></span>
                    </p>
                    <p>
                        <strong>2022-12-23</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/viz/viz_join.html" target="_blank">表join关系图</a></span>
                    </p>
                    <p>
                        <strong>2022-04-07</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/mergely/examples/simple.html" target="_blank">文本对比工具</a></span>
                    </p>
                    <p>
                        <strong>2020-05-26</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/viz/viz_template2.html?table=dim_oristar_cmc_base_sale_channel" target="_blank">表关系图</a></span><br/>
                        <!--                        <span  class="change_log_line"><a href="js/plugin/viz/viz_template2.html?table=CINEMA.dw_pos_movie_ticket_order_collect&action=all" target="_blank">表关系图</a></span><br/>-->
                    </p>
                    <p>
                        <strong>2020-02-06</strong><br/>
                        <span class="change_log_line"><a href="sql_translate.html" target="_blank">sql转换</a></span>
                    </p>
                </div>
            </div>
        </div>
    </div>


    <div style="display: none;">
        <table summary="" id="defaultsTemplate" class="tableTemplate tablesorter tablesorter-default" style="display: none;">
            <thead class="thTemplate">
                <tr class="info textCenter"><th scope="col" style="display: none;"> </th></tr>
            </thead>
            <tbody class="trTemplate">
                <tr class="tinfo phrase_tr" data-id="#{id}"> </tr>
            </tbody>
        </table>
    </div>

    <!-- login Modal -->
    <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close login_close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title" id="loginModalLabel">登录账户</h4>
                </div>
                <div class="modal-body">
                    <div class="input-group">
                        <span class="input-group-addon">账户</span>
                        <input type="text" class="form-control" placeholder="登录的帐户名" name="username"/>
                    </div>
                    <div class="input-group">
                        <span class="input-group-addon">密码</span>
                        <input type="password" class="form-control" placeholder="密码" name="password"/>
                    </div>
                </div>
                <div class="modal-footer">
                    <span class="prompt"></span>
                    <button type="button" class="btn btn-default login_close" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary login_submit">登录</button>
                </div>
            </div>
        </div>
    </div>
</div>
<span class="silver">代码版本:</span> <span class="sybn_ver silver"></span>
</body>
<script type="text/javascript" src="js/plugin/select2/select2.min.js"></script>
<link rel="stylesheet" href="js/plugin/select2/select2.min.css">

<script>

function login_action(username) {
    var query_request_id = getQueryString("request_id") || "";
    if (query_request_id) {
        replayHistory(query_request_id);
    }
}

$(document).ready(function() {
    showVersion('api/job_v2/version.json', $('.sybn_ver'), "text")

    var query_api_base = getQueryString("api_base") || "";
    var query_api_version = getQueryString("api_version") || "";
    var query_api_mode = getQueryString("api_mode") || "";
    var query_api_query = getQueryString("api_query") || "";
    var query_api_cache = getQueryString("api_cache") || "";
    var query_tenant_id = getQueryString("tenant_id") || "";
    var query_cinema_id = getQueryString("cinema_id") || "";
    var query_request_id = getQueryString("request_id") || "";

    if (query_api_version) {
        $('[name=apiVersion]').val(query_api_version);
    }
    if (query_api_mode) {
        $('[name=modelName]').val(query_api_mode);
    }
    if (query_api_query) {
        $('[name=userQuery]').val(unzip(query_api_query));
    }
    if (query_api_cache) {
        $('[name=cacheAble]').val(query_api_cache);
    }
    if (query_tenant_id) {
        $(".tenant_select").val(query_tenant_id);
    }
    if (query_cinema_id) {
        $(".cinema_select").val(query_cinema_id);
    }
    if (query_request_id) {
        replayHistory(query_request_id);
    }

    $('body').on('click', '.gbiApi', function(e) {
        // 主接口地址
        var api = query_api_base + ($(this).data("api") || "api/chatbot/chat.json");
        var userQuery = $('[name=userQuery]').val();
        var modelName = $('[name=modelName]').val();
        var apiVersion = $('[name=apiVersion]').val();
        var cacheAble = $('[name=cacheAble]').val();
        var tenant_id = $(".tenant_select").val()
        var cinema_id = $(".cinema_select").val()



        var url2 = window.location.href.toString()
        url2 = changeURLPar(url2, "api_mode", modelName);
        url2 = changeURLPar(url2, "api_version", apiVersion);
        url2 = changeURLPar(url2, "api_query", zip(userQuery));
        url2 = changeURLPar(url2, "api_cache", cacheAble);
        url2 = changeURLPar(url2, "tenant_id", tenant_id);
        url2 = changeURLPar(url2, "cinema_id", cinema_id);
        window.history.pushState({},0,url2);

        loadingIndicator.style.display = 'block';
        document.getElementById('view_param').innerHTML = userQuery + "<br/>思考中...";

        var button = $(this);
        button.prop('disabled', true);
        var startTime = new Date().getTime();

        var aj = $.ajax({
          url : api,
          type : 'post',
          data : {query : userQuery, modelName: modelName, apiVersion: apiVersion, cacheAble: cacheAble, tenantId: tenant_id, cinemaId: cinema_id},
          cache : false,
          dataType : 'json',
          async : true,
          success : function(data) {
            button.prop('disabled', false);
            showResult(data, startTime);
          },
          error : function(data) {
            button.prop('disabled', false);
            document.getElementById('resultMsg').value = `请求失败`;
            loadingIndicator.style.display = 'none';
          }
        });
    });
    $(".view_param").empty().append($(".view_param_1").clone().children());

    const loadingIndicator = document.getElementById('loadingIndicator');
    loadingIndicator.style.display = 'none';

    var panel_type = getQueryString("panel_type");
    if (panel_type == 'xs') {
        $("body").addClass("panel_type_xs")
    }

    // 绑定点击事件（使用 on 指定动态元素）
    $(document).on('click', '.positiveButton', function () {
        var requestId = $(this).data('request_id');
        var event = event || window.event;
        $.post('api/chatbot/positive', { requestId: requestId }, function (res) {
            if (res.result === true) {
                showCopySuccessMessage(event, "已点赞");
            } else {
                showCopySuccessMessage(event, "操作失败：" + res.msg);
            }
        }).fail(function () {
            showCopySuccessMessage(event, "网络错误，请重试");
        });
    });

    $(document).on('click', '.negativeButton', function () {
        var requestId = $(this).data('request_id');
        var event = event || window.event;
        $.post('api/chatbot/negative', { requestId: requestId }, function (res) {
            if (res.result === true) {
                showCopySuccessMessage(event, "已踩");
            } else {
                showCopySuccessMessage(event, "操作失败：" + res.msg);
            }
        }).fail(function () {
            showCopySuccessMessage(event, "网络错误，请重试");
        });
    });

    // 下拉搜索框
    $(".tenant_select").select2({
        data: [],
        placeholder:'请选择租户(默认不限)',
        allowClear: true,
        ajax: {
            url: 'https://bi.oristarcloud.com/dw-api-dwapp/api/dynamic_sql/impl/public/public_api_tenant_id.json?_result_platform=cx4',
            type:'post',
            dataType: 'json',
            delay: 250,
            cache: true,
            data: function (params) {
                return {
                    search: params.term
                };
            },
            processResults: function (data) {
                return {
                    results: data.data.map(item => ({ id: item.k, text: item.v}))
                };
            }
         }
    })

    // 下拉搜索框
    $(".cinema_select").select2({
        data: [],
        placeholder:'请选择影院(默认不限)',
        allowClear: true,
        cache: true,
        ajax: {
            url: 'https://bi.oristarcloud.com/dw-api-dwapp/api/dynamic_sql/impl/public/public_api_cinema_uid_search_all_tenant.json',
            type:'post',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    name: params.term,
                    tenant_id: $(".tenant_select").val()
                };
            },
            processResults: function (data) {
                return {
                    results: data.rows.map(item => ({ id: item.k, text: item.v}))
                };
            }
         }
    })


    // 下拉搜索框
    $(".history_select").select2({
        data: [],
        placeholder:'查询历史问题',
        allowClear: true,
        cache: true,
        ajax: {
            url: '/dw-api-core/api/chatbot/history',
            type:'post',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    search: params.term,
                };
            },
            processResults: function (data) {
                return {
                    results: data.rows.map(item => ({ id: item.requestId, text: item.startTime + " " + item.query}))
                };
            }
         } // ,
         // templateResult: function (item) {
         //     if (!item.id) return item.text;
         //     // 使用 jQuery 解析 HTML 字符串并返回 DOM 元素
         //     return $(item.text);
         // }
    })

});

// 设置sql
var setGbiFun = function(t) {
    var setGbi;
    if (typeof t != 'string' && t.value != undefined) {
         setGbi = t.value;
    }
    if (!setGbi) {
        return;
    }
    var s = $('[name=userQuery]').val(setGbi);
}

// 回放历史提问
var replayHistory = function(t) {
    var requestId;
    if (typeof t == 'string') {
         requestId = t;
    } else if (typeof t != 'string' && t.value != undefined) {
         requestId = t.value;
    }
    if (!requestId) {
        return;
    }
    var startTime = new Date().getTime();
    var aj = $.ajax({
          url : "api/chatbot/history_full.json?admin=true&requestId=" + requestId,
          type : 'get', cache : false, dataType : 'json', async : true,
          success : function(data) {
            if (data && !data.result && data.msg == "请先登录") {
                $('#loginModal').modal({show:true,backdrop:'static',keyboard:false});
                $('.login_close').hide();
                return;
            }
            if (data && data.result && data.rows) {
                let historyRes = data.rows[0];
                if (historyRes) {
                    $('[name=userQuery]').val(historyRes.query);
                    $(".tenant_select").val(historyRes.tenantId);
                    $(".cinema_select").val(historyRes.cinemaIds);
                    showResult(historyRes);
                    var url2 = changeURLPar(window.location.href.toString(), "request_id", historyRes.requestId || '');
                    window.history.pushState({},0,url2);
                }
            }
          },
          error : function(data) {

          }
        });
}

var showResult = function(data, startTime) {
    if (data && !data.result && data.msg == "请先登录") {
        $('#loginModal').modal({show:true,backdrop:'static',keyboard:false});
        $('.login_close').hide();
        return;
    }
    if (data && data.resultMsg) {

        document.getElementById('resultMsg').value = data.resultMsg + (data.reasoningContent ? "\r\n\r\n-----AI理推理逻辑：----\r\n"+data.reasoningContent : '');
        document.getElementById('knowledge').innerHTML = data.knowledge;
        var inputTokens = data.inputTokens;
        var outputTokens = data.outputTokens;
        var time = (data.endTime || '') + " (" + (data.costTimeMills / 1000).toFixed(2) + "秒)";
        var tkFee = " <b>inputTokens: </b>" + inputTokens + " <b>outputTokens: </b>" + outputTokens + " <b title='"+(inputTokens/1000)+"*0.0016元+"+(outputTokens/1000)+"*0.004元"+"'>预计费用: </b>"+ (inputTokens/1000*0.0016+outputTokens/1000*0.004).toFixed(4) +"元";
        var positive = ' <button class="btn btn-success positiveButton padding1" data-request_id="'+data.requestId+'"><i class="fa fa-thumbs-up"></i>顶</button><button class="btn btn-warning negativeButton padding1" data-request_id="'+data.requestId+'"><i class="fa fa-thumbs-down"></i>踩</button>'
        document.getElementById('prompt').innerHTML = time + " <b>sessionId:</b>" + (data.sessionId ? data.sessionId : '-') + " <b>requestId:</b>" + data.requestId + tkFee + positive + " <span class='silver'>" + costTimeToStr(data) + "</span>";

    } else {
        document.getElementById('resultMsg').value = "";
        document.getElementById('knowledge').innerHTML = data.knowledge;
    }


    if (data && data.msg.trim() == '智能回答') {
        loadingIndicator.style.display = 'none';
        $("#outputTable").text();
        return;
    }

    // 显示表格
    var resData = (data && data.resData) ? data.resData : [];
    var $p = $("#outputTable");
    resetPreviewTabs($p);
    var view_id = setPreviewTabs($p);
    //格式化json
    var $jsonView = $p.find('.json_view');
    var rowsLength = resData.length;
    if (resData && resData.length <= 500) {
        // 如果返回值在500行以内，将json格式化显示
        $jsonView.JSONView(data);
    } else if (resData && resData.length >= 1000) {
        // 如果返回值在1000行以上，不格式化返回值, 并仅保留最多1000行
        resData.splice(1000, resData.length-2);
        var jsonData = JSON.stringify(resData);
        $jsonView.text(jsonData);
        $jsonView.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，已禁用json格式化, 并仅保留最多1000行。</div>");
    } else {
        // 如果返回值在500行以上，不格式化返回值，因为格式化太大json会卡死浏览器
        var jsonData = JSON.stringify(resData);
        $jsonView.text(jsonData);
        $jsonView.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，已禁用json格式化。</div>");
    }

    // 显示表格
    // class=fixed
    $jsonView.after("<div id='view_table_"+view_id+"' class='iframe_preview tab-pane'><table class='table table-condensed tableTarget table-striped table-bordered table-hover margin0 tablesorter tablesorter-default'><thead><tr class='info'><th>-</th></tr></thead><tbody class='trTarget max-height200'><tr><td class='prompt'>暂无数据</td></tr></tbody></table></div>");
    var $iframe_preview = $jsonView.parent().find(".iframe_preview");

    var endTime = new Date().getTime();
    showDatasByDataGbi(resData, $iframe_preview, startTime ? (endTime-startTime) : null, data.query);

    if (data.resError) {
      document.getElementById('prompt').innerHTML += "<br/><span class='red'>"+data.resError+"</span>"
    }
    loadingIndicator.style.display = 'none';
}

var costTimeToStr = function(data) {
    var costTime = "";
    var total = data.costTimeMills; // 总耗时作为分母

    if (total > 0) {
        var parts = [];

        if (data.costTimeMillsRewrite > 0) {
            var percent = ((data.costTimeMillsRewrite / total) * 100).toFixed(0);
            parts.push(`rewrite: ${(data.costTimeMillsRewrite / 1000).toFixed(2)}s(${percent}%)`);
        }

        if (data.costTimeMillsKnowledge > 0) {
            var percent = ((data.costTimeMillsKnowledge / total) * 100).toFixed(0);
            parts.push(`knowledge: ${(data.costTimeMillsKnowledge / 1000).toFixed(2)}s(${percent}%)`);
        }

        if (data.costTimeMillsSqlGen > 0) {
            var percent = ((data.costTimeMillsSqlGen / total) * 100).toFixed(0);
            parts.push(`sqlGen: ${(data.costTimeMillsSqlGen / 1000).toFixed(2)}s(${percent}%)`);
        }

        if (data.costTimeMillsSqlRun > 0) {
            var percent = ((data.costTimeMillsSqlRun / total) * 100).toFixed(0);
            parts.push(`sqlRun: ${(data.costTimeMillsSqlRun / 1000).toFixed(2)}s(${percent}%)`);
        }

        if (data.costTimeMillsResult > 0) {
            var percent = ((data.costTimeMillsResult / total) * 100).toFixed(0);
            parts.push(`${(data.costTimeMillsResult / 1000).toFixed(2)}s(${percent}%)`);
        }

        if (data.costTimeMillsChart > 0) {
            var percent = ((data.costTimeMillsChart / total) * 100).toFixed(0);
            parts.push(`chart: ${(data.costTimeMillsChart / 1000).toFixed(2)}s(${percent}%)`);
        }

        if (data.costTimeMillsOther > 0) {
            var percent = ((data.costTimeMillsOther / total) * 100).toFixed(0);
            parts.push(`other: ${(data.costTimeMillsOther / 1000).toFixed(2)}s(${percent}%)`);
        }

        if (parts.length > 0) {
            costTime = parts.join(" ");
        } else {
            costTime = "";
        }
    } else {
        costTime = "";
    }
    return costTime;
};


var showDatasByDataGbi = function(resData, $div, currentSecMills, filename) {
    $view_div = $div.closest('.view_div');
    $view_div.find('.tab_rows').text('');
    if (resData && resData.length > 0) {
        loadDataToTable(resData, $div, "#defaultsTemplate");
        $div.find(".tablesorter").tablesorter();
        $view_div.find('.tab_view_table').click();
        var text = "返回["+resData.length+"]条结果 ";
        if (currentSecMills) {
            var currentSec = currentSecMills / 1000;
            text += (currentSec > 100 ? currentSec.toFixed(0) + "秒 " : currentSec.toFixed(2) + "秒 ");
        }

        $view_div.find('.tab_rows').text(text);
        if (resData.length <= 1000) {
            // 导出数据  为 csv 文件
            var csvDownload = $("<a href='###' title='直接导出以下表格的数据到csv文件' >导出表格</a>")
            csvDownload.on("click", function(){downloadJson2Csv(resData, filename)});
            var csvDownloadLi = $("<li class='tab_clear' style='float:right'></li>")
            csvDownloadLi.append(csvDownload);
            $view_div.find('.tab_rows').closest('li').before(csvDownloadLi);

            // 复制到粘贴板
            var tsvDownload = $("<a href='###' title='复制以下表格的数据到粘贴板' >复制到粘贴板</a>")
            tsvDownload.on("click", function(){downloadJson2Tsv(resData)});
            var tsvDownloadLi = $("<li class='tab_clear' style='float:right'></li>")
            tsvDownloadLi.append(tsvDownload);
            $view_div.find('.tab_rows').closest('li').before(tsvDownloadLi);
        }

        var tableFixed = $("<a href='###' title='对齐列宽' >对齐列宽</a>")
        tableFixed.on("click", function(){
            $table = $view_div.find('table');
            if ($table.hasClass("tableFixed")) {
                $table.removeClass("tableFixed");
                $(this).removeClass("active");
            } else {
                $table.addClass("tableFixed");
                $(this).addClass("active");
            }
        });
        var tableFixedLi = $("<li class='tab_tableFixed' style='float:right'></li>")
        tableFixedLi.append(tableFixed);

        if (resData.length > 1000) {
            $dev.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，只显示前1000条数据，如需导出大量数据，建议直接导出csv。</div>");
        }
        $view_div.find('.tab_rows').closest('li').before(tableFixedLi);

    } else {
        $div.find('.prompt').text('没有查询到数据!');
        resData = [{"-":"没有查询到数据!"}];
        loadDataToTable(resData, $div, "#defaultsTemplate");
        $view_div.find('.tab_view_table').click();
        var text = "返回["+0+"]条结果 ";
        if (currentSecMills) {
            var currentSec = currentSecMills / 1000;
            text += (currentSec > 100 ? currentSec.toFixed(0) + "秒 " : currentSec.toFixed(2) + "秒 ");
        }

        $view_div.find('.tab_rows').text(text);
    }

}
function checkYearMissing(userQuery) {
    const pattern = /(?<!年)([0-9,—\-\u81F3]+月)/g;

    let match;
    let errors = [];

    while ((match = pattern.exec(userQuery)) !== null) {
        // 如果匹配成功，说明找到了“缺乏年份的月”
        errors.push(`"${match[0]}" 缺乏年份`);
    }

    if (errors.length > 0) {
        var choice = window.confirm("当前提问可能缺少年份, 很可能无法查询到正确结果, 是否继续查询当前内容? \r\n" + errors.join("\n"));
        return choice;
    }

    return true;
}
</script>
</html>
